package lium.lbs.lbsim.chat

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.graphics.drawable.AnimationDrawable
import android.net.Uri
import android.os.*
import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.Gravity
import android.view.MotionEvent
import android.view.View
import android.widget.ImageView
import android.widget.PopupWindow
import android.widget.TextView
import com.chad.library.adapter.base.BaseQuickAdapter
import com.lmlibrary.Constants
import lium.lbs.lbsim.activity.BaseActivity
import lium.lbs.lbsim.utils.ToastUtils
import com.lqr.audio.AudioRecordManager
import com.lqr.audio.IAudioRecordListener
import com.luck.picture.lib.PictureSelector
import com.luck.picture.lib.entity.LocalMedia
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.activity_chat.*
import kotlinx.android.synthetic.main.msg_add_layout.*
import kotlinx.android.synthetic.main.msg_emoji_layout.*
import lium.lbs.lbsim.R
import lium.lbs.lbsim.chat.activity.LMMessage
import lium.lbs.lbsim.chat.activity.MsgSendStatus
import lium.lbs.lbsim.chat.activity.MsgType
import lium.lbs.lbsim.chat.bean.*
import lium.lbs.lbsim.chat.utils.MediaManager
import lium.lbs.lbsim.chat.utils.PictureFileUtil
import lium.lbs.lbsim.utils.IAlertDialog
import java.io.File
import java.util.*

abstract class ChatBaseActivity : BaseActivity(), SwipeRefreshLayout.OnRefreshListener,
    BaseQuickAdapter.OnItemChildClickListener {

    val REQUEST_CODE_IMAGE = 1
    val REQUEST_CODE_CAMERA = 1111 //拍摄
    val REQUEST_CODE_VEDIO = 2222 //录制

    var isInitVoiceButton=false
    var isInitPhotoButton=false

    companion object {
        val mSenderId = "right"
        val mTargetId = "left"
    }
    override fun getLayoutId(): Int {  return R.layout.activity_chat }
    var mAdapter:ChatAdapter?=null
    var msglist = arrayListOf<LMMessage>()

    private var tempAudio: ImageView? = null
    override fun initView(savedInstanceState: Bundle?) {
        var right_img = findViewById<ImageView>(R.id.right_img)
        right_img.setImageResource(R.drawable.icon_more)
        right_img.visibility=View.VISIBLE

        mAdapter = ChatAdapter(this, msglist)
        val mLinearLayout = LinearLayoutManager(this)
        rv_chat_list.layoutManager = mLinearLayout
        rv_chat_list.adapter = mAdapter
        swipe_chat.setOnRefreshListener(this)
        mAdapter!!.onItemChildClickListener = this
        initChatUi()
        initVoiceListener()
        addOnClickListeners(R.id.btn_send,R.id.rlPhoto,R.id.rlVideo,R.id.right_img)
    }

    private fun initChatUi() {
        val mUiHelper = ChatUiHelper.with(this)
        mUiHelper.bindContentLayout(llContent)
        .bindttToSendButton(btn_send)
            .bindEditText(et_content)
            .bindBottomLayout(bottom_layout)
            .bindEmojiLayout(rlEmotion)
            .bindAddLayout(llAdd)
            .bindToAddButton(ivAdd)
            .bindToEmojiButton(ivEmo)
            .bindAudioBtn(btnAudio)
            .bindAudioIv(ivAudio)
        //底部布局弹出,聊天列表上滑
        rv_chat_list.addOnLayoutChangeListener { v, left, top, right, bottom, oldLeft, oldTop, oldRight, oldBottom ->
            if (bottom < oldBottom) {
                rv_chat_list.post {
                    if (mAdapter!!.itemCount > 0) {
                        rv_chat_list.smoothScrollToPosition(mAdapter!!.itemCount - 1)
                    }
                }
            }
        }
    }


    override fun onRefresh() {
        val mReceiveMsgList = ArrayList<LMMessage>()
        val mMessgaeText = getBaseReceiveMessage(MsgType.TEXT)
        val mTextMsgBody = TextMsgBody()
        mTextMsgBody.message = "收到的消息"
        mMessgaeText.body=mTextMsgBody
        mReceiveMsgList.add(mMessgaeText)
        val mMessgaeImage = getBaseReceiveMessage(MsgType.IMAGE)
        val mImageMsgBody = ImageMsgBody()
        mImageMsgBody.setThumbUrl("https://img-bbs.csdn.net/upload/201707/17/1500286923_459579.jpg")
        mMessgaeImage.body=mImageMsgBody
        mReceiveMsgList.add(mMessgaeImage)
        mAdapter!!.addData(0, mReceiveMsgList)
        swipe_chat.isRefreshing = false
    }

    override fun onClick(v: View?) {
        super.onClick(v)
        when(v!!.id){
            R.id.btn_send ->{
                sendTextMsg(et_content.text.toString())
                et_content.setText("")
            }
            R.id.rlPhoto -> {
                if(isInitPhotoButton || Build.VERSION.SDK_INT < 23){
                    PictureFileUtil.openGalleryPic(this@ChatBaseActivity, REQUEST_CODE_IMAGE)
                }else{
                    requestPhotoPermissions()
                }
            }
            R.id.rlVideo -> {
                val intent = Intent(this, RecordVideoActivity::class.java)
                startActivityForResult(intent,REQUEST_CODE_VEDIO)
            }
        }
    }
    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        ToastUtils.showToast("功能开发中...")
        if (tempAudio!=null){
            tempAudio!!.setBackgroundResource(R.mipmap.audio_animation_list_right_3)
            tempAudio=null
            MediaManager.reset()
        }else{
            MediaManager.reset()
            tempAudio = view!!.findViewById(R.id.ivAudio)
            tempAudio!!.setBackgroundResource(R.drawable.audio_animation_right_list)
            val drawable = tempAudio!!.background as AnimationDrawable
            drawable.start()
            MediaManager.playSound(
                this@ChatBaseActivity, (mAdapter!!.data[position].body as AudioMsgBody).localPath
            ) {
                tempAudio!!.setBackgroundResource(R.mipmap.audio_animation_list_right_3)
                MediaManager.release()
            }
        }
    }
    override fun getNetWorkData() {
    }


    //文本消息
    private fun sendTextMsg(inputtext: String) {
        val mMessgae = getBaseSendMessage(MsgType.TEXT)
        val mTextMsgBody = TextMsgBody()
        mTextMsgBody.message = inputtext
        mMessgae.body=mTextMsgBody
        //开始发送
        mAdapter!!.addData(mMessgae)
        //模拟两秒后发送成功
        updateMsg(mMessgae)
    }

    //语音消息
    fun OnFinishedRecord(file: File,voiceTime:Int){
        ToastUtils.showToast("录音测试成功")
        file?.let {
            if (file.exists()){
                sendAudioMessage(file.absolutePath, voiceTime)
            }
        }
    }
    //语音消息
    private fun sendAudioMessage(path: String, time: Int) {
        val mMessgae = getBaseSendMessage(MsgType.AUDIO)
        val mFileMsgBody = AudioMsgBody()
        mFileMsgBody.localPath = path
        mFileMsgBody.duration= time.toLong()
        mMessgae.body=mFileMsgBody
        //开始发送
        mAdapter!!.addData(mMessgae)
        //模拟两秒后发送成功
        updateMsg(mMessgae)
    }

    //图片消息
    private fun sendImageMessage(media: LocalMedia) {
        val mMessgae = getBaseSendMessage(MsgType.IMAGE)
        val mImageMsgBody = ImageMsgBody()
        mImageMsgBody.thumbUrl = media.compressPath
        mMessgae.body=mImageMsgBody
        //开始发送
        mAdapter!!.addData(mMessgae)
        //模拟两秒后发送成功
        updateMsg(mMessgae)
    }


    //视频消息
    private fun sendVedioMessage(thumbnailPath:String,recordPath:String) {
        val mMessgae = getBaseSendMessage(MsgType.VIDEO)
        val mImageMsgBody = VideoMsgBody()
        mImageMsgBody.localPath = recordPath
        mImageMsgBody.extra = thumbnailPath
        mMessgae.body=mImageMsgBody
        //开始发送
        mAdapter!!.addData(mMessgae)
        //模拟两秒后发送成功
        updateMsg(mMessgae)

    }

    private fun updateMsg(mMessgae: LMMessage) {
        rv_chat_list.scrollToPosition(mAdapter!!.itemCount - 1)
        //模拟2秒后发送成功
        Handler().postDelayed({
            var position = 0
            mMessgae.sentStatus=MsgSendStatus.SENT
            //更新单个子条目
            for ((index,bean) in mAdapter!!.data.withIndex()){
                //if (mMessgae.equals(bean.uuid)) {
                if (TextUtils.equals(bean.uuid,bean.uuid)) {
                    position = index
                }
            }
            mAdapter!!.notifyItemChanged(position)
        }, 1000)

    }

    private fun getBaseSendMessage(msgType: MsgType): LMMessage {
        val mMessgae = LMMessage(
            UUID.randomUUID().toString(), //var uuid: String,
            "", //var msgId: String,
            msgType, //var msgType: MsgType,
            null, //var body: MsgBody,
            MsgSendStatus.SENDING,  //var sentStatus: MsgSendStatus,
            mSenderId,  // var senderId: String,
            mTargetId, //var targetId: String,
            System.currentTimeMillis()
        )
        return mMessgae
    }

    private fun getBaseReceiveMessage(msgType: MsgType): LMMessage {
        val mMessgae = LMMessage(
            UUID.randomUUID().toString(), //var uuid: String,
            "", //var msgId: String,
            msgType, //var msgType: MsgType,
            null, //var body: MsgBody,
            MsgSendStatus.SENDING,  //var sentStatus: MsgSendStatus,
            mTargetId,  // var senderId: String,
            mSenderId, //var targetId: String,
            System.currentTimeMillis()
        )
        return mMessgae
    }


    //-------语音模块功能


    private fun requestVoicePermissions() {
        val rxPermission = RxPermissions(this)
        rxPermission.request(
            Manifest.permission.RECORD_AUDIO
            , Manifest.permission.WRITE_EXTERNAL_STORAGE
            , Manifest.permission.WAKE_LOCK
            , Manifest.permission.READ_EXTERNAL_STORAGE
        )
            .subscribe { granted ->
                if (granted!!) {
                    isInitVoiceButton = true
                } else {
                    requestPerFailed(resources.getString(R.string.app_name)+"需要语音和文件存储权限，请到设置开启权限允许")
                }
            }
    }

    internal var dialog: IAlertDialog? = null
    public fun requestPerFailed(msg:String) {
        dialog = IAlertDialog(this, IAlertDialog.LayoutStyle.THEME_WHITE_TITLE_SINGLEBUTTON, Gravity.CENTER)
        dialog!!.setMessage(msg)
        dialog!!.setPositiveMsg("确定")
        dialog!!.show()
    }
    private fun initVoiceListener() {
        //临时缓存文件夹
        val tempFile = File(Environment.getExternalStorageDirectory(), Constants.VOICE_CACHE_DIR)
        if (!tempFile.exists()) {
            tempFile.mkdirs()
        }
        AudioRecordManager.getInstance(this).maxVoiceDuration = 30
        AudioRecordManager.getInstance(this).setAudioSavePath(tempFile.absolutePath)
        btnAudio.setOnTouchListener { v, event ->
            if(isInitVoiceButton || Build.VERSION.SDK_INT < 23){
                when (event.action) {
                    MotionEvent.ACTION_DOWN -> {
                        AudioRecordManager.getInstance(this).startRecord()
                    }
                    MotionEvent.ACTION_MOVE -> {
                        if (isCancelled(v, event)) {
                            AudioRecordManager.getInstance(this).willCancelRecord()
                        } else {
                            AudioRecordManager.getInstance(this).continueRecord()
                        }
                    }
                    MotionEvent.ACTION_UP -> {
                        AudioRecordManager.getInstance(this).stopRecord()
                        AudioRecordManager.getInstance(this).destroyRecord()
                    }
                }
            }else{
                requestVoicePermissions()
            }

            false
        }

        AudioRecordManager.getInstance(this).audioRecordListener = object : IAudioRecordListener {
            val timeHandler = object : Handler() {
                override fun handleMessage(msg: Message) {
                    when (msg.what) {
                        100 ->{
                            mStateTV?.text = countTime.toString()+"\""
                        }
                    }
                }
            }

            private var mTimerTV: TextView? = null
            private var mStateTV: TextView? = null
            private var mStateIV: ImageView? = null
            private var mRecordWindow: PopupWindow? = null
            private var timer: Timer?=null
            private var countTime=0
            override fun initTipView() {
                val view = View.inflate(this@ChatBaseActivity, R.layout.popup_audio_wi_vo, null)
                mStateIV = view.findViewById<View>(R.id.rc_audio_state_image) as ImageView
                mStateTV = view.findViewById<View>(R.id.rc_audio_state_text) as TextView
                mTimerTV = view.findViewById<View>(R.id.rc_audio_timer) as TextView
                mRecordWindow = PopupWindow(view, -1, -1)
                mRecordWindow!!.showAtLocation(llContent, 17, 0, 0)
                mRecordWindow!!.isFocusable = true
                mRecordWindow!!.isOutsideTouchable = false
                mRecordWindow!!.isTouchable = false
            }
            fun stopTimeTask(){
                countTime=0
                if (timer!=null ){
                    timer!!.purge()
                    timer!!.cancel()
                }
            }
            override fun setTimeoutTipView(counter: Int) {
                stopTimeTask()
                if (this.mRecordWindow != null) {
                    this.mStateIV!!.visibility = View.GONE
                    this.mStateTV!!.visibility = View.VISIBLE
                    this.mStateTV!!.setText(R.string.voice_rec)
                    this.mStateTV!!.setBackgroundResource(R.drawable.bg_voice_popup)
                    this.mTimerTV!!.text = String.format("%s", *arrayOf<Any>(Integer.valueOf(counter)))
                    this.mTimerTV!!.visibility = View.VISIBLE
                }
            }

            override fun setRecordingTipView() {

                if (this.mRecordWindow != null) {
                    this.mStateIV!!.visibility = View.VISIBLE
                    this.mStateIV!!.setImageResource(R.mipmap.ic_volume_1)
                    this.mStateTV!!.visibility = View.VISIBLE
                    //this.mStateTV!!.setText(R.string.voice_rec)
                    this.mStateTV!!.setBackgroundResource(R.drawable.bg_voice_popup)
                    this.mTimerTV!!.visibility = View.GONE
                }
            }

            override fun setAudioShortTipView() {
                stopTimeTask()
                if (this.mRecordWindow != null) {
                    mStateIV!!.setImageResource(R.mipmap.ic_volume_wraning)
                    mStateTV!!.setText(R.string.voice_short)
                }
            }

            override fun setCancelTipView() {
                stopTimeTask()
                if (this.mRecordWindow != null) {
                    this.mTimerTV!!.visibility = View.GONE
                    this.mStateIV!!.visibility = View.VISIBLE
                    this.mStateIV!!.setImageResource(R.mipmap.ic_volume_cancel)
                    this.mStateTV!!.visibility = View.VISIBLE
                    this.mStateTV!!.setText(R.string.voice_cancel)
                    this.mStateTV!!.setBackgroundResource(R.drawable.corner_voice_style)
                }
            }

            override fun destroyTipView() {
                stopTimeTask()
                if (this.mRecordWindow != null) {
                    this.mRecordWindow!!.dismiss()
                    this.mRecordWindow = null
                    this.mStateIV = null
                    this.mStateTV = null
                    this.mTimerTV = null
                }
            }
            override fun onStartRecord() {
                countTime = 0
                if(timer!=null ){
                    timer!!.purge()
                    timer!!.cancel()
                    timer=null
                }
                //开始录制
                timer = Timer()
                timer!!.schedule(object : TimerTask() {
                    override fun run() {
                        countTime++
                        timeHandler.sendEmptyMessage(100)
                    }
                }, 0, 1000)
            }

            override fun onFinish(audioPath: Uri, duration: Int) {
                stopTimeTask()
                //发送文件
                val file = File(audioPath.path)
                if (file.exists()) {
                    OnFinishedRecord(file,duration)
                }
            }

            override fun onAudioDBChanged(db: Int) {
                when (db / 5) {
                    0 -> this.mStateIV!!.setImageResource(R.mipmap.ic_volume_1)
                    1 -> this.mStateIV!!.setImageResource(R.mipmap.ic_volume_2)
                    2 -> this.mStateIV!!.setImageResource(R.mipmap.ic_volume_3)
                    3 -> this.mStateIV!!.setImageResource(R.mipmap.ic_volume_4)
                    4 -> this.mStateIV!!.setImageResource(R.mipmap.ic_volume_5)
                    5 -> this.mStateIV!!.setImageResource(R.mipmap.ic_volume_6)
                    6 -> this.mStateIV!!.setImageResource(R.mipmap.ic_volume_7)
                    else -> this.mStateIV!!.setImageResource(R.mipmap.ic_volume_8)
                }
            }
        }
    }


    private fun isCancelled(view: View, event: MotionEvent): Boolean {
        val location = IntArray(2)
        view.getLocationOnScreen(location)
        return event.rawX < location[0] || event.rawX > location[0] + view.width || event.rawY < location[1] - 40
    }

    // 相册
    private fun requestPhotoPermissions() {
        val rxPermission = RxPermissions(this)
        rxPermission.request(
            Manifest.permission.WRITE_EXTERNAL_STORAGE
            , Manifest.permission.WRITE_EXTERNAL_STORAGE
        )
            .subscribe { granted ->
                if (granted!!) {
                    isInitPhotoButton = true
                } else {
                    requestPerFailed(resources.getString(R.string.app_name)+"需要相册权限，请到设置开启权限允许")
                }
            }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                REQUEST_CODE_IMAGE -> {
                    // 图片选择结果回调
                    val selectListPic = PictureSelector.obtainMultipleResult(data)
                    for (media in selectListPic) {
                        sendImageMessage(media)
                    }
                }
            }
        }else{
            when(resultCode){
                REQUEST_CODE_CAMERA -> {
                    var imagePath =data!!.getStringExtra("imagePath")
                    var localMedia:LocalMedia= LocalMedia()
                    localMedia.compressPath = imagePath
                    sendImageMessage(localMedia)
                }
                REQUEST_CODE_VEDIO -> {
                    var thumbnailPath = data!!.getStringExtra("thumbnailPath")
                    var recordPath = data!!.getStringExtra("recordPath")
                    sendVedioMessage(thumbnailPath,recordPath)

                }
            }
        }

    }
}